package com.pushtime.service.lib.engine;

import com.pushtime.config.Constants;
import com.pushtime.service.dto.JhipsterDTO;
import com.pushtime.service.dto.YeomanDTO;
import com.pushtime.service.util.InflectorUtil;
import org.apache.commons.lang3.text.WordUtils;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class KeyWordTemplate implements BaseTemplate {

    private final InflectorUtil inflectorUtil = InflectorUtil.getInstance();

    private final VagueMachingTemplate vagueMachingTemplate;

    public KeyWordTemplate(VagueMachingTemplate vagueMachingTemplate) {
        this.vagueMachingTemplate = vagueMachingTemplate;
    }

    @Override
    public Matcher replace(Pattern pattern, Matcher matcher, JhipsterDTO jhipsterDTO, YeomanDTO yeomanDTO, String group) {
        if (!group.startsWith("{{") || !group.endsWith("}}")) {
            throw new IllegalArgumentException("argument error!");
        }
        String key = group.substring(2, group.length() - 2).trim();
        String value;
        switch (key) {
            case "packageName":
                value = yeomanDTO.getGeneratorJhipster().getPackageName();
                break;
            case "extra":
                value = Constants.GENERATE_DIR;
                break;
            case "Extra":
                value = Constants.GENERATE_SUFFIX;
                break;
            case "Entity":
                value = jhipsterDTO.getName();
                break;
            case "entity":
                value = WordUtils.uncapitalize(jhipsterDTO.getName());
                break;
            case "entity-url":
                value = inflectorUtil.tableize(jhipsterDTO.getName());
                break;
            default:
                return vagueMachingTemplate.replace(pattern, matcher, jhipsterDTO, yeomanDTO, group);
        }
        String result = matcher.replaceFirst(value);
        matcher = pattern.matcher(result);
        return matcher;
    }
}
